package io.hepu.robotize.controller;

import io.hepu.robotize.storage.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

@RestController
@RequestMapping("/files")
public class FileController {

    private final IFileService fileService;

    @Autowired
    public FileController(IFileService fileService) {
        this.fileService = fileService;
    }

    /**
     * 上传文件
     * 使用 boundedElastic 线程池处理阻塞操作
     *
     * @param sessionId Websocket 会话Id
     * @param file      上传的文件
     */
    @PostMapping("/{sessionId}")
    public Mono<String> uploadFile(@PathVariable String sessionId, @RequestPart("file") MultipartFile file) {
        return Mono.fromCallable(() -> fileService.upload(file, sessionId))
                .subscribeOn(Schedulers.boundedElastic());
    }

    /**
     * 下载文件
     * 使用 boundedElastic 线程池处理阻塞操作
     *
     * @param fileName  文件名
     * @param sessionId Websocket 会话Id
     * @param response  ServerHttpResponse
     */
    @GetMapping("/{sessionId}/{fileName}")
    public Mono<Object> downloadFile(@PathVariable String fileName, @PathVariable String sessionId, ServerHttpResponse response) {
        return Mono.fromRunnable(() -> {
            try {
                fileService.download(fileName, sessionId, response);
            } catch (Exception e) {
                e.printStackTrace();
                response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }).subscribeOn(Schedulers.boundedElastic());
    }
}
